package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 创建用户（事务支持）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public User createUser(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.selectByUsername(user.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在: " + user.getUsername());
        }
        
        // 检查邮箱是否已存在
        existingUser = userMapper.selectByEmail(user.getEmail());
        if (existingUser != null) {
            throw new RuntimeException("邮箱已存在: " + user.getEmail());
        }
        
        // 保存用户
        userMapper.insert(user);
        return user;
    }

    /**
     * 根据ID查询用户（只读事务）
     */
    @Override
    @Transactional(readOnly = true)
    public Optional<User> getUserById(Long id) {
        User user = userMapper.selectById(id);
        return Optional.ofNullable(user);
    }

    /**
     * 查询所有用户（只读事务）
     */
    @Override
    @Transactional(readOnly = true)
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }

    /**
     * 根据用户名查询用户（只读事务）
     */
    @Override
    @Transactional(readOnly = true)
    public Optional<User> getUserByUsername(String username) {
        User user = userMapper.selectByUsername(username);
        return Optional.ofNullable(user);
    }

    /**
     * 根据姓名模糊查询用户（只读事务）
     */
    @Override
    @Transactional(readOnly = true)
    public List<User> searchUsersByName(String name) {
        return userMapper.selectByNameContaining(name);
    }
}

